package com.hlx.exception;

import com.hlx.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@ResponseBody
@ControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.info(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry") && ex.getMessage().contains("'user.user_account'")) {
            String[] arr = ex.getMessage().split(" ");
            return Result.error(arr[2] + "用户已存在！");
        }
        else if(ex.getMessage().contains("Duplicate entry") && ex.getMessage().contains("'customer.customer_Identity'")) {
            return Result.error("身份证不正确！");
        }else if(ex.getMessage().contains("TooManyResultsException") && ex.getMessage().contains("but found: 2")){
            return Result.error("禁止同一个人同一时间段买俩张票");
        }
        return Result.error("未知错误！");
    }
}